package com.example.mapStore;

import cn.hutool.core.io.FileUtil;
import com.example.dto.UserDto;
import com.hazelcast.map.MapStore;
import io.fury.Fury;
import io.fury.config.Language;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.*;

public class MapStoreImpl implements MapStore<String, UserDto> {

    Logger logger = LoggerFactory.getLogger(getClass());

    private static final String DIR = "e://data//";

    private Fury fury;

    public Fury getFury() {
        if (this.fury == null) {
            this.fury = Fury.builder().withLanguage(Language.JAVA).requireClassRegistration(true).build();
            this.fury.register(UserDto.class);
        }
        return this.fury;
    }

    /***
     * 保存操作
     * @param key   key of the entry to store
     * @param value value of the entry to store
     */
    @Override
    public void store(String key, UserDto value) {
        byte[] bytes = getFury().serialize(value);
        FileUtil.writeBytes(bytes, DIR + key);
    }

    /***
     * 保存多个
     * @param map map of entries to store
     */
    @Override
    public void storeAll(Map<String, UserDto> map) {
        for (String key : map.keySet()) {
            UserDto userDto = map.get(key);
            this.store(key, userDto);
        }
    }

    /***
     * 删除对象
     * @param key the key to delete from the store
     */
    @Override
    public void delete(String key) {
        FileUtil.del(DIR + key);
    }

    /***
     * 删除多个
     * @param keys the keys of the entries to delete.
     */
    @Override
    public void deleteAll(Collection<String> keys) {
        for (String key : keys) {
            this.delete(key);
        }
    }

    /***
     * 加载对象
     * @param key
     * @return
     */
    @Override
    public UserDto load(String key) {
        File file = new File(DIR + key);
        if (file.exists()) {
            byte[] bytes = FileUtil.readBytes(DIR + key);
            return (UserDto) getFury().deserialize(bytes);
        }
        return null;
    }

    /***
     * 根据key加载多个
     * @param keys keys of the values entries to load
     * @return
     */
    @Override
    public Map<String, UserDto> loadAll(Collection<String> keys) {
        Map<String, UserDto> map = new HashMap<>();
        for (String key : keys) {
            UserDto userDto = this.load(key);
            map.put(key, userDto);
        }
        return map;
    }

    /***
     * 加载所有的keys
     * @return
     */
    @Override
    public Iterable<String> loadAllKeys() {
        String[] arr = new File(DIR).list();
        if (arr == null || arr.length == 0) {
            return new ArrayList<>();
        }
        return Arrays.asList(arr);
    }
}
